class_name NinefoldCalamityBlockEffect
extends Effect

# 记录卡牌使用时的回合数
var turn_used: int = -1
# 音效引用（基类Effect已有sound变量，这里只需要optional_sound）
var optional_sound: AudioStream = null


func execute(targets: Array[Node]) -> void:
	print("🛡️ 九重灾劫术护甲效果执行")
	
	if targets.size() == 0:
		print("❌ 没有目标")
		return
	
	var player = targets[0]
	if not player or not player.stats:
		print("❌ 无效的玩家目标")
		return
	
	# 获取battle引用
	var battle = _get_battle_from_player(player)
	if not battle:
		print("❌ 无法获取battle引用")
		return
	
	# 计算护甲值：基于敌人回合结束时玩家受到的伤害
	var block_amount = _calculate_block_amount(player, battle)
	
	if block_amount > 0:
		# 给予护甲
		player.stats.gain_block(block_amount)
		print("🛡️ 九重灾劫术给予护甲: %d (基于本回合敌人伤害)" % block_amount)
		
		# 播放音效（优先使用基类的sound，其次使用optional_sound）
		if sound:
			SFXPlayer.play(sound)
		elif optional_sound:
			SFXPlayer.play(optional_sound)
	else:
		print("🛡️ 九重灾劫术：本回合未受到伤害，护甲值为0")
	
	print("🔄 九重灾劫术效果完成")


# 计算护甲值
func _calculate_block_amount(player: Node, battle: Node) -> int:
	if not player.stats or not player.stats.get_stats_tracker():
		return 0
	
	var stats_tracker = player.stats.get_stats_tracker()
	var combat_tracker = stats_tracker.get_combat_tracker()
	
	if not combat_tracker:
		return 0
	
	# 获取本回合玩家受到的伤害
	var damage_taken = combat_tracker.total_damage_taken
	print("📊 九重灾劫术计算护甲：本回合受到伤害 %d" % damage_taken)
	
	return damage_taken


# 从玩家获取battle引用
func _get_battle_from_player(player: Node) -> Node:
	if not player.get_tree():
		return null
	
	return player.get_tree().get_first_node_in_group("battle") 